'use strict';

/**
 * 系统配置Controller
 */
app.controller('SysConfigCtrl', 
	['$scope', 'dialogs', 'SysConfigService',
	function($scope, dialogs, SysConfigService) {
	var vm = $scope.vm = this;
	
	vm.tabsId = 0;
	vm.pwdNotRepeatCounts = [];

	for(var i = 1; i < 11; i++){
		vm.pwdNotRepeatCounts.push(i);
	}
	
	var init = function(){
		SysConfigService.init().then(function(data){
			var mail = {};
			var sec = {};
			//邮件配置
			angular.forEach(data.mail, function(da, index){
				mail[da.key] = da.value;
			});
			//语言
			vm.langs = data.lang;
			angular.forEach(vm.langs, function(v, index){
				if(v.code == mail.mail_lang){
					mail.mail_lang = v;
				}
			});
			vm.mail = mail;
			//安全配置
			angular.forEach(data.sec, function(da, index){
				sec[da.key] = da.value;
			});
			angular.forEach(vm.pwdNotRepeatCounts, function(v, index){
				if(v == sec.sec_pwd_not_repeat_count){
					sec.sec_pwd_not_repeat_count = v;
				}
			});
			vm.sec = sec;
		
		});
	}

	init();

	vm.mailTestFlag = false;
	//修改邮件信息要重新测试
	$scope.$watch('vm.mail', function(newValue, oldValue) {
		vm.mailTestFlag = false;
	},true);
	
	vm.reloadPage = function(){
		init();
	}

	//测试连接
	vm.testLink = function(){
		var param = {
			'smtp':vm.mail.mail_smtp_server,
			'username':vm.mail.mail_account,
			'password':vm.mail.mail_password
		};
		SysConfigService.testLink(param).then(function(data){
			if(data.success){
				vm.mailTestFlag = true;
				dialogs.notify(data);
			}else{
				var msg = "";
				if(data.errorCode == 1){
					msg = ISS.getMessage("sysConfig.AuthException");
				}else if(data.errorCode == 2){
					msg = ISS.getMessage("sysConfig.ConnectionException");
				}else if(data.errorCode == 3){
					msg = ISS.getMessage("sysConfig.ConnectionException");
				}
				dialogs.notify(null, msg);
			}
		});
	}
	
	//mail submit
	vm.mailSubmit = function(){
		if(vm.mailTestFlag){
			var submitData = [];
			angular.forEach(vm.mail, function(value, key){
				if(key == 'mail_lang'){
					value = value.code;
				}
				var data = {key: key, value: value};
				submitData.push(data);
			});
			SysConfigService.mailSubmit(submitData).then(function(data){
				dialogs.notify(data);
			});
		}
	}
	//user submit
	vm.secSubmit = function(){
		var submitData = [];
		angular.forEach(vm.sec, function(value, key){
			var data = {key: key, value: value};
			submitData.push(data);
		});
		SysConfigService.userSubmit(submitData).then(function(data){
			dialogs.notify(data);
		});
	}
	
}]);
